import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Select, Button, message } from 'antd';

import { getSpecialtyByAcademyId } from '../../../api/specialty';
import { getAcademyInfo } from '../../../api/academy';
import { getTeacherInfoByAcademyId } from '../../../api/teacher';

const { Option } = Select;

// 中文数字映射（支持到99）
const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十'];

const numberToChinese = (num) => {
    if (num <= 10) return chineseNumbers[num];
    const tens = Math.floor(num / 10);
    const units = num % 10;
    let result = '';
    if (tens > 0) result += chineseNumbers[tens] + '十';
    if (units > 0) result += chineseNumbers[units];
    return result;
};

const ClassModal = ({ visible, onCancel, onOk, editingRecord }) => {
    const [form] = Form.useForm();
    const [academyList, setAcademyList] = useState([]);
    const [specialtyList, setSpecialtyList] = useState([]);
    const [teacherList, setTeacherList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [academyLoading, setAcademyLoading] = useState(false);
    const [selectedAcademyId, setSelectedAcademyId] = useState(null);
    const [years, setYears] = useState([]);

    const handleYearChange = (value) => {
        const year = String(value).slice(-2);
        form.setFieldsValue({
            grade: year
        });
    };
    // 生成最近 N 年的选项
    useEffect(() => {
        const currentYear = new Date().getFullYear();
        const yearOptions = [];

        for (let i = currentYear; i >= 2000; i--) {
            yearOptions.push(i);
        }

        setYears(yearOptions);
    }, []);

    // 获取学院列表
    const fetchAcademyInfo = async () => {
        setLoading(true);
        try {
            const res = await getAcademyInfo(null);
            setAcademyList(res.data || []);
        } catch (error) {
            message.error('获取学院列表失败');
            console.error(error);
        } finally {
            setLoading(false);
        }
    };

    // 根据学院 ID 获取专业列表
    const fetchSpecialtyList = async (academyId) => {
        if (!academyId) return;
        setAcademyLoading(true);
        try {
            const res = await getSpecialtyByAcademyId(academyId);
            setSpecialtyList(res.data || []);
        } catch (error) {
            message.error('获取专业列表失败');
            console.error(error);
        } finally {
            setAcademyLoading(false);
        }
    };

    // 根据学院 ID 获取教师列表
    const fetchTeacherList = async (academyId) => {
        if (!academyId) return;
        setAcademyLoading(true);
        try {
            const res = await getTeacherInfoByAcademyId(academyId);
            setTeacherList(res.data || []);
        } catch (error) {
            message.error('获取教师列表失败');
            console.error(error);
        } finally {
            setAcademyLoading(false);
        }
    };

    // 学院改变事件
    const handleAcademyChange = (value) => {
        setSelectedAcademyId(value);
        fetchSpecialtyList(value);
        fetchTeacherList(value);
        form.setFieldsValue({
            specialtyId: undefined,
            classCode: '',
            className: ''
        });
    };

    // 专业改变事件，自动生成班级编号和名称
    const handleSpecialtyChange = (value) => {
        const selectedSpecialty = specialtyList.find(s => s.id === value);
        if (!selectedSpecialty) return;

        let nextNo = 1;
        if (selectedSpecialty.maxClassCode) {
            const currentNo = parseInt(selectedSpecialty.maxClassCode, 10);
            nextNo = isNaN(currentNo) ? 1 : currentNo + 1;
        }

        const paddedNextNo = nextNo.toString().padStart(2, '0'); // 补零
        const chineseNo = numberToChinese(nextNo);
        const className = `${selectedSpecialty.specialtyName}${chineseNo}班`;

        form.setFieldsValue({
            classCode: paddedNextNo,
            className: className
        });
    };

    // 初始化数据
    useEffect(() => {
        if (visible) {
            fetchAcademyInfo();

            if (editingRecord) {
                form.setFieldsValue(editingRecord);
                if (editingRecord.academyId) {
                    setSelectedAcademyId(editingRecord.academyId);
                    fetchSpecialtyList(editingRecord.academyId);
                    fetchTeacherList(editingRecord.academyId);
                }
            } else {
                form.resetFields();
                setSpecialtyList([]);
                setTeacherList([]);
                setSelectedAcademyId(null);
            }
        }
    }, [visible, editingRecord]);


    const handleOk = async () => {
        try {
            await form.validateFields();

            const values = form.getFieldsValue();

            if (!values.academyId || !values.specialtyId || !values.teacherId) {
                message.error("请先选择学院、专业和导师");
                return;
            }

            if (!editingRecord && !values.grade) {
                message.error("请先选择创建年份");
                return;
            }

            setLoading(true);
            form.validateFields()
                .then(values => {
                    onOk(values);
                    form.resetFields();
                    setSpecialtyList([]);
                    setTeacherList([]);
                    setSelectedAcademyId(null);
                })
                .catch(error => {
                    console.log('验证失败:', error);
                });
            setLoading(false);
        } catch (error) {
            console.error(error);
            setLoading(false);
        }
    };

    return (
        <Modal
            title={editingRecord ? '编辑班级信息' : '新增班级信息'}
            open={visible}
            onOk={handleOk}
            onCancel={onCancel}
            footer={[
                <Button key="cancel" onClick={onCancel}>取消</Button>,
                <Button key="submit" type="primary" onClick={handleOk}>提交</Button>
            ]}
        >
            <Form form={form} layout="vertical" name="class_form">
                {/* 所属学院 */}
                {/* 所属学院 */}
                <Form.Item label="所属学院" name="academyId" rules={[{ required: true, message: '请选择学院' }]}>
                    <Select
                        showSearch
                        loading={loading}
                        placeholder="请选择学院"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                            option.children.toLowerCase().includes(input.toLowerCase())
                        }
                        onChange={handleAcademyChange}
                    >
                        {academyList.map(academy => (
                            <Option key={academy.id} value={academy.id}>
                                {academy.academyName}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                {/* 所属专业 */}
                <Form.Item label="所属专业" name="specialtyId" rules={[{ required: true, message: '请选择专业' }]}>
                    <Select
                        showSearch
                        loading={academyLoading}
                        disabled={!selectedAcademyId}
                        placeholder="请先选择学院"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                            option.children.toLowerCase().includes(input.toLowerCase())
                        }
                        onChange={handleSpecialtyChange}
                    >
                        {specialtyList.map(specialty => (
                            <Option key={specialty.id} value={specialty.id}>
                                {specialty.specialtyName}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                {/* 班级导师 */}
                <Form.Item label="班级导师" name="teacherId" rules={[{ required: true, message: '请选择班级导师' }]}>
                    <Select
                        showSearch
                        loading={academyLoading}
                        disabled={!selectedAcademyId}
                        placeholder="请先选择学院"
                        optionFilterProp="children"
                        filterOption={(input, option) =>
                            option.children.toLowerCase().includes(input.toLowerCase())
                        }
                    >
                        {teacherList.map(teacher => (
                            <Option key={teacher.id} value={teacher.id}>
                                {teacher.teacherName}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                {/* 创建年份 */}
                <Form.Item
                    label="创建年份"
                    name="grade"
                    rules={[{ required: !editingRecord, message: '请选择创建年份' }]}
                    hidden={editingRecord}
                >
                    <Select
                        placeholder="请选择年份"
                        style={{ width: '100%' }}
                        onChange={handleYearChange}
                        showSearch
                        filterOption={(input, option) =>
                            option.children.toString().toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                    >
                        {years.map(year => (
                            <Option key={year} value={year}>
                                {year}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>

                {/* 班级名称 */}
                <Form.Item label="班级名称" name="className" rules={[{ required: true, message: '班级名称不能为空' }]}>
                    <Input placeholder="自动生成" readOnly />
                </Form.Item>

                {/* 班级代码 */}
                <Form.Item label="班级代码" name="classCode" rules={[{ required: true, message: '班级代码不能为空' }]}>
                    <Input placeholder="自动生成" readOnly />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default ClassModal;